<?php

namespace bc\model\wc;

use bc\ar\MActiveRecord;
use bc\model\UserModel;
use bc\wx\Auth;
use bc\wx\User as User;

class DoctorModel extends MActiveRecord
{

    /**
     * 定义数据表
     */
    public static function tableName()
    {
        return '{{%wc_doctor}}';
    }

    /**
     * bc_hospital表实体名
     */
    protected function getHospitalModelName()
    {
        return HospitalModel::tableName();
    }

    /**
     * bc_hospital表实体名
     */
    protected function getUserModelName()
    {
        return UserModel::tableName();
    }

    /*
     * 获取医生列表
     * */
    public function getDoctorList($params, $page = null, $pageSize = null, $oderBy = null)
    {
        $ar = $this->find ()->select ( $this->columns )->leftJoin ( $this->getHospitalModelName(), self::getTableSchema ()->name . '.hospital_id=' . $this->getHospitalModelName() . '.id' )->leftJoin ( $this->getUserModelName(), self::getTableSchema ()->name . '.user_id=' . $this->getUserModelName() . '.id' );
        if ($params)
        {
            $ar->where ( $params );
        }
        if ($page && $pageSize)
        {
            $offset = $this->getOffset ( $page, $pageSize );
            $ar->offset ( $offset )->limit ( $pageSize );
        }

        if ($this->sort != null)
            $ar->orderBy ( $oderBy );
        // $ar->groupBy ( 'id' );
        return $ar->asArray ()->all ();
    }

    /*
     * 根据openid获取医生数据
     * */
    public function getDoctorFromOpenid($openid)
    {
        $dao = new MActiveRecord();
        $sql = 'select a.id as aid ,b.id as bid,c.id as cid,a.*,b.*,c.* from bc_user a,bc_wc_doctor b,bc_wx_user c where b.user_id=a.id and c.id= a.wx_user_id and a.wxid="'.$openid.'"';
        $row = $dao->getDb()->createCommand($sql)->queryOne();
        return $row;
    }

    /*
     * 获取某个月分某个医生推广数据
     * $size:整数，当前月份减几个月
     * $d_id：医生的openid
     * */
    public function getPromotelist($size,$d_id)
    {
        $tmp_date=date("Ym");
        $tmp_date = date("Ym",strtotime("$tmp_date"." $size month"));
        $tmp_year=substr($tmp_date,0,4);
        $tmp_mon =substr($tmp_date,4,2);
        $forwardmonth_utc=mktime(0,0,0,$tmp_mon,1,$tmp_year);
        $endmonth_utc=mktime(0,0,0,$tmp_mon+1,1,$tmp_year);

        $where =  ' doctor_id='. $d_id . ' and create_time >= '.$forwardmonth_utc.' and create_time < '.$endmonth_utc;

        $sql = 'select * from bc_wc_booking where ' . $where;
        $dao = new MActiveRecord();
        $row = $dao->getDb()->createCommand($sql)->queryAll();
        $row1['data'] = $row;
        $row1['tmp_year']=$tmp_year;
        $row1['tmp_mon']=$tmp_mon;
        return $row1;
    }
}